<?php

namespace support;

use OSS\OssClient;
use OSS\Core\OssException;
use app\services\ConfigService;
use Qiniu\Storage\UploadManager;

class AliOssStore
{
    protected $accessKeyId;
    protected $accessKeySecret;
    protected $bucketName;
    protected $endpoint;

    protected $config;

    protected $ossClient;

    public function __construct()
    {
        $this->config = $config = ConfigService::getByGroup('aliyun_oss');

        if (empty($config) || empty($config['access_key_id']) || empty($config['access_key_secret']) || empty($config['bucket_name']) || empty($config['endpoint'])) {
            throw new \Exception('请在后台配置阿里云OSS');
        }

        $this->accessKeyId = $config['access_key_id'];
        $this->accessKeySecret = $config['access_key_secret'];
        $this->bucketName = $config['bucket_name'];
        $this->endpoint = $config['endpoint'];

        $this->ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
    }

    public function upload($request, $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'fjr', 'd4', 'r20', 'xml'])
    {
        $file = $request->file('file');

        $extension = strtolower($file->getUploadExtension());

        if (!in_array($extension, $allowedExtensions)) {
            return err_rsp('不正确的文件扩展');
        }

        $fileName = 'userUpload/' . microtime(true) * 1000 . '.' . $extension;
        $relativePath = '/' . $fileName;
        $absolutePath = public_path() . dirname($relativePath);

        // Check if the directory exists, if not, create it
        if (!is_dir($absolutePath)) {
            mkdir($absolutePath, 0755, true);
        }

        $file->move($absolutePath . '/' . basename($relativePath));

        try {
            $this->ossClient->uploadFile($this->bucketName, $fileName, $absolutePath . '/' . basename($relativePath));

            return $this->config['oss_url'] . '/' . $fileName;
        } catch (OssException $e) {
            throw new \Exception('上传失败: ' . $e->getMessage());
        }
    }

    public function uploadLocalToRemote($localPath, $remotePath)
    {
        return $this->ossClient->uploadFile($this->bucketName, $remotePath, $localPath);
    }
}